<template>
  <el-container style="height:100%;position:relative;">
    <el-aside style="width:230px;padding:10px 10px;">
      <div class="role-list">部门列表</div>
      <el-scrollbar style="height:100%;  width: 230px;" class="el-role-tree">
        <el-tree
          :data="data"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </el-scrollbar>
    </el-aside>

    <el-main style="padding:10px 10px;">

      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
        <el-form-item>
          <el-input
            v-model="filter.name"
            placeholder="名称"
            clearable
            @keyup.enter.native="onSearch"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-search" @click="onSearch">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysrole_add'])">
          <el-button icon="el-icon-plus" type="primary" @click="onAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="listLoading"
        border
        :data="orgs"
        highlight-current-row
        :header-cell-style="{background:'#f9f9f9'}"
      >
        <el-table-column type="index" width="80" label="#" />
        <el-table-column prop="name" label="部门名称" width />
        <el-table-column prop="sort" label="排序" width />

        <el-table-column prop="createTime" label="创建时间" :formatter="formatCreatedTime" width />
        <el-table-column label="操作" width="180">
          <template #default="{ $index, row }">

            <el-button v-if="checkPermission(['admin_sysorganize_update'])" type="success" icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
            <my-confirm-button
              v-if="checkPermission(['admin_sysorganize_delete'])"
              type="delete"
              icon="el-icon-delete"
              :loading="row._loading"
              :validate-data="row"
              @click="onDelete($index, row)"
            />
          </template>
        </el-table-column>

      </el-table>

      <my-pagination
        ref="pager"
        :total="total"
        @get-page="loadList"
      />

      <!--新增窗口-->
      <el-dialog
        title="新增部门"
        :visible.sync="addFormVisible"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
          <el-form-item prop="parentId" label="父级部门">
            <el-cascader
              :key="addFormkey"
              v-model="addForm.parentId"
              placeholder="请选择，支持搜索功能"
              :options="modules"
              :props="{ checkStrictly: true, value: 'id'}"
              filterable
              style="width:100%;"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" auto-complete="off" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="addForm.sort" auto-complete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
          </div>
        </template>
      </el-dialog>

      <!--编辑窗口-->
      <el-dialog
        title="编辑"
        :visible.sync="editFormVisible"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px" size="medium">
          <el-form-item prop="parentId" label="上级部门">
            <el-cascader
              :key="editFormKey"
              v-model="editForm.parentId"
              placeholder="请选择，支持搜索功能"
              :options="modules"
              :props="{ checkStrictly: true, value: 'id'}"
              filterable
              style="width:100%;"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="editForm.name" auto-complete="off" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="editForm.sort" auto-complete="off" />
          </el-form-item>

        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :validate="editFormValidate" :loading="editLoading" @click="onEditSubmit" />
          </div>
        </template>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<script>
import { formatTime, getTreeParents } from '@/utils'
import { getOrgTree, getOrgListPage, removeOrg, addOrg, editOrg, getOrg } from '@/api/admin/organize'
import MyConfirmButton from '@/components/my-confirm-button'
export default {
  name: 'Orgs',
  components: { MyConfirmButton },
  data() {
    return {
      filter: {
        name: '',
        id: ''
      },
      orgs: [],
      data: [],
      total: 0,
      listLoading: false,
      modules: [],
      pageLoading: false,
      addFormVisible: false,
      addFormRef: null,
      deleteLoading: false,
      addLoading: false,
      editFormKey: 1,
      addFormkey: 1,
      addFormRules: {
        parentId: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      editFormRules: {
        parentId: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        parentId: '',
        sort: 0,
        name: ''
      },
      editFormVisible: false,
      editForm: {
        parentId: '',
        name: '',
        sort: 0
      },
      editLoading: false
    }
  },
  mounted() {
    this.loadTree()
    this.loadList()
  },
  beforeUpdate() {
  },
  methods: {
    async loadTree() {
      const res = await getOrgTree()
      const root = {
        id: '0',
        parentId: '',
        label: '根节点',
        children: []
      }
      this.modules = []
      root.children = res.data
      ++this.addFormkey
      this.modules.push(root)
      this.data = res.data
    },
    async loadList() {
      var pager = this.$refs.pager.getPager()
      const params = {
        ...pager,
        id: this.filter.id,
        name: this.filter.name
      }
      this.listLoading = true
      const res = await getOrgListPage(params)
      this.listLoading = false
      if (!res?.success) {
        return
      }
      this.total = res.data.totalCount
      const data = res.data.rows
      data.forEach(d => {
        d._loading = false
      })
      this.orgs = data
    },
    handleNodeClick(data) {
      this.filter.id = data.id
      // 发送请求获取子节点
      this.loadList()
    },
    formatCreatedTime: function(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD HH:mm')
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const res = await removeOrg(JSON.stringify(row.id))
      row._loading = false
      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.loadTree()
      this.loadList()
    },
    onSearch() {
      this.$refs.pager.setPage(1)
      this.loadList()
    },
    // 显示新增界面
    onAdd() {
      this.addFormVisible = true
    },
    // 新增
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.parentId = para.parentId.pop()
      const res = await addOrg(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.loadList()
      this.loadTree()
    },
    async onEditSubmit() {
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      if (Array.isArray(para.parentId)) {
        para.parentId = para.parentId.pop()
      }
      if (para.id === para.parentId) {
        this.$message({
          message: '上级部门不能是自己！',
          type: 'error'
        })
        this.editLoading = false
        return
      }

      const res = await editOrg(para)
      this.editLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.loadTree()
      this.loadList()
    },
    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      const res = await getOrg({ id: row.id })
      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.data, row.id)
        const parentIds = parents.map(p => p.id)
        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editFormVisible = true
        ++this.editFormKey
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.role-list {
  color: white;
  line-height: 30px;
  background: #409eff;
  font-size: 16px;
  width: 230px;
}
</style>
